import db from "@/utils/Dexie";
import useStore from "@/store/index";
const store = useStore();
export const getStatusColor = (status) => {
	const statusColors = {
		待下发: "#faad14",
		进行中: "#1890ff",
		已完成: "#52c41a",
		工长审批: "#52c41a",
		技管审批: "#722ed1",
		归档: "#8c8c8c",
	};
	return statusColors[status] || "#8c8c8c";
};
export const convertDict = (dictName, type, target) => {
	const targetDict = store.dict.find((item) => item.name === dictName);
	if (!targetDict || !targetDict.children || targetDict.children.length === 0) {
		console.warn(`未找到名称为${dictName}的字典组或该字典组无数据`);
		return null;
	}
	const children = targetDict.children;
	let result = null;
	if (type === "v2l") {
		const matched = children.find((item) => item.value == target);
		result = matched ? matched.label : null;
	} else if (type === "l2v") {
		const matched = children.find((item) => item.label === target);
		result = matched ? matched.value : null;
	}
	if (result === null) {
		console.warn(`在${dictName}中未找到${type === "v2l" ? "value" : "label"}为${target}的匹配项`);
	}
	return result;
};
export const getTransformedDict = (dictName, type) => {
	const dictItem = store.dict.find((item) => item.name === dictName);
	if (!dictItem || !dictItem.children) {
		return [{ text: "全部" + type, value: null }];
	}
	const transformed = dictItem.children.map((item) => ({
		text: item.label,
		value: item.value,
	}));
	transformed.sort((a, b) => {
		return Number(a.value) - Number(b.value);
	});
	return [{ text: "全部" + type, value: null }, ...transformed];
};
export const base64ToObjectUrl = (base64String, type) => {
	const base64Content = base64String.split(",")[1] || base64String;
	const byteCharacters = atob(base64Content);
	const byteNumbers = new Array(byteCharacters.length);
	for (let i = 0; i < byteCharacters.length; i++) {
		byteNumbers[i] = byteCharacters.charCodeAt(i);
	}
	const byteArray = new Uint8Array(byteNumbers);
	return URL.createObjectURL(new Blob([byteArray], { type }));
};
export const base64ToFile = (base64String, fileName, mimeType) => {
	const base64Data = base64String.split(",")[1];
	const byteCharacters = atob(base64Data);
	const byteArrays = [];
	for (let offset = 0; offset < byteCharacters.length; offset += 512) {
		const slice = byteCharacters.slice(offset, offset + 512);
		const byteNumbers = new Array(slice.length);
		for (let i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}
		const byteArray = new Uint8Array(byteNumbers);
		byteArrays.push(byteArray);
	}
	const blob = new Blob(byteArrays, { type: mimeType });
	return new File([blob], fileName, { type: mimeType });
};
export const errorNotify = (fileName, functionName, error) => {
	const now = new Date();
	const timeStr =
		now.getFullYear() +
		"-" +
		String(now.getMonth() + 1).padStart(2, "0") +
		"-" +
		String(now.getDate()).padStart(2, "0") +
		" " +
		String(now.getHours()).padStart(2, "0") +
		":" +
		String(now.getMinutes()).padStart(2, "0") +
		":" +
		String(now.getSeconds()).padStart(2, "0");
	const errorMessage = error?.message || String(error);
	const backendMsg = error?.response?.data?.msg || "";
	const errorMsg = `[${timeStr}]${fileName}：${functionName}\n${errorMessage}${backendMsg ? `\n${backendMsg}` : ""}\n(请截图并提报问题工单)`;
	console.error(errorMsg, error);
	showNotify({
		type: "danger",
		message: errorMsg,
		duration: 0,
	});
};
export const deepEqual = (a, b) => {
	if (a === b) {
		return true;
	}
	if (a == null || b == null || typeof a !== "object" || typeof b !== "object") {
		return false;
	}
	if (a.constructor !== b.constructor) {
		return false;
	}
	if (a instanceof Date && b instanceof Date) {
		return a.getTime() === b.getTime();
	}
	if (a instanceof RegExp && b instanceof RegExp) {
		return a.toString() === b.toString();
	}
	const keysA = Object.keys(a);
	const keysB = Object.keys(b);
	if (keysA.length !== keysB.length) {
		return false;
	}
	for (let key of keysA) {
		if (!b.hasOwnProperty(key)) {
			return false;
		}
		if (!deepEqual(a[key], b[key])) {
			return false;
		}
	}
	return true;
};
export const extractAllOptionsToJson = (htmlString) => {
	const parser = new DOMParser();
	const doc = parser.parseFromString(htmlString, "text/html");
	const result = {};
	const selects = doc.querySelectorAll("select");
	selects.forEach((select) => {
		const placeholderOption = select.querySelector("option[value='']");
		let key = "";
		if (placeholderOption) {
			key = placeholderOption.textContent.trim().replace("选择", "");
		}
		if (!key) return;
		const options = Array.from(select.querySelectorAll("option"))
			.filter((option) => option.value.trim() !== "")
			.map((option) => ({
				value: option.value,
				label: option.textContent.trim(),
			}));
		result[key] = options;
	});
	return result;
};
export const clearAllCaches = async () => {
	try {
		store.clearAll();
		const tableNames = db.tables.map((table) => table.name);
		const clearPromises = tableNames.map((tableName) => db.table(tableName).clear());
		await Promise.all(clearPromises);
	} catch (error) {
		errorNotify("Misc.js", "clearAllCaches", error);
		throw error;
	}
};

/**
 * 使用图片对象检测网络连接状态
 * @param {string} url - 要检测的图片URL，默认为百度favicon
 * @param {number} timeoutMs - 超时时间（毫秒），默认5000ms
 * @returns {Promise<boolean>} - 网络是否连接
 */
export const pingServer = (url = "https://www.google.com/favicon.ico", timeoutMs = 5000) => {
	return new Promise((resolve) => {
		const img = new Image();
		const timestamp = new Date().getTime();
		const finalUrl = `${url}?${timestamp}`;
		const timeout = setTimeout(() => {
			resolve(false);
		}, timeoutMs);

		img.onload = () => {
			clearTimeout(timeout);
			resolve(true);
		};

		img.onerror = () => {
			clearTimeout(timeout);
			resolve(false);
		};

		img.src = finalUrl;
	});
};
